import React, { PureComponent } from 'react';
import { Card, Button, Form, Col, Row, Input, Select, message, Upload, Icon, Checkbox } from 'antd';
import { connect } from 'dva';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './RoomForm.less';
import { fieldLabelList, getBase64, beforeUpload, supportingList } from './utils';

const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;

// add room info component
@connect(state => ({
  ...state.meetingRoom,
}))
@Form.create()
export default class MeetingRoomUpdateForm extends PureComponent {
  state = {
    imageUrl: '',
  }
  // image change handler
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false,
      }));
    }
  }

  // validate forms
  validate = () => {
    const { validateFieldsAndScroll } = this.props.form;
    const { dispatch } = this.props;
    const handleSuccSave = (response) => {
      if (response.http_status === '201') {
        message.success('创建成功');
      }
    };

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        // submit the values
        const saveVal = {
          ...values,
          item: values.item.join('  '),
          space_id: 2,
          cover: 'cover.url',
        };
        dispatch({
          type: 'meetingRoom/add',
          payload: saveVal,
          callback: handleSuccSave,
        });
      }
    });
  }

  // render form item accord filed
  renderFormItem = (field) => {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 12,
      },
    };

    let content = <Input placeholder={field.placeholder} />;
    if (field.name === 'big') {
      content = (
        <Select placeholder="请选择类型">
          <Option value="1">场地</Option>
          <Option value="0">会议室</Option>
        </Select>
      );
    }
    if (field.name === 'label') {
      content = (
        <TextArea placeholder={length.placeholder} />
      );
    }
    if (field.name === 'item') {
      content = (
        <CheckboxGroup options={supportingList} />
      );
    }
    return (
      <Form.Item
        hasFeedback
        {...formItemLayout}
        label={field.label}
        key={field.name}
      >
        {getFieldDecorator(field.name, {
          rules: field.rules,
        })(content)}
      </Form.Item>
    );
  }

  // render room forms
  renderForms = () => {
    const chunkSize = fieldLabelList.length / 2;
    const renderList = fieldLabelList.reduce((acc, cur, index) => {
      const chunkIndex = Math.floor(index / chunkSize);
      if (!acc[chunkIndex]) {
        acc[chunkIndex] = {
          data: [],
          key: chunkIndex,
        };
      }
      // assign chunk to fields
      const fields = acc[chunkIndex];
      fields.data.push(cur);
      // return accurate
      return acc;
    }, []);

    return renderList.map((fields) => {
      // const key = Math.random() * 10;
      return (
        <Col span={8} key={fields.key}>
          {fields.data.map(this.renderFormItem)}
        </Col>
      );
    });
  }

  render() {
    const { loading } = this.props;
    const { imageUrl } = this.state;
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    const submitFormLayout = {
      wrapperCol: {
        span: 24,
        offset: 4,
      },
    };

    return (
      <PageHeaderLayout
        title="新建会场"
        wrapperClassName={styles.advancedForm}
      >
        <Card title="新建会场信息" className={styles.card} bordered={false}>
          <Form layout="vertical" hideRequiredMark>
            <Row gutter={24}>
              <Col span={16}>
                {this.renderForms()}
              </Col>
              <Col span={8}>
                <Upload
                  name="avatar"
                  listType="picture-card"
                  className="avatar-uploader"
                  showUploadList={false}
                  action="//p0irncapn.bkt.clouddn.com"
                  beforeUpload={beforeUpload}
                  onChange={this.handleChange}
                >
                  {imageUrl ? <img src={imageUrl} alt="cover" /> : uploadButton}
                </Upload>
              </Col>
            </Row>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button type="primary" onClick={this.validate} htmlType="submit" loading={loading}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderLayout>
    );
  }
}
